#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pthread.h>
#include <memory.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sys/time.h>
#include <fcntl.h>
#include "Fpga.h"
#include "AHB.h"
#include "ChooseCmd.h"
typedef struct sockaddr Sockaddr;
typedef struct sockaddr_in Sockaddr_in;
extern unsigned char mutex; //ahb互斥锁
extern unsigned char server_mutex;
int main()
{
    Open_FPGA();
    int ret;
    int listensock;
    Sockaddr_in addr_in;
    //listensock = socket(AF_INET, SOCK_STREAM,0);
    listensock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listensock == -1)
    {
        return -1;
    }
    //设置地址重用，避免前面异常错误退出后，无法绑定套接字
    int on = 1;
    ret = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    memset(&addr_in, 0, sizeof(Sockaddr));
    addr_in.sin_family = AF_INET;
    addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
    addr_in.sin_port = htons(5000);
    ret = bind(listensock, (Sockaddr *)&addr_in, sizeof(addr_in));

    //互斥锁初始化
    mutex = 0;
    server_mutex = 0;
    //

    if (ret == -1)
    {
        return -2;
    }
    listen(listensock, 1024);
    int consock;
    while (1)
    {
        Sockaddr_in addr;
        socklen_t addr_len = sizeof(addr); //必须初始化地址长度
        consock = accept(listensock, (Sockaddr *)&addr, &addr_len);
        if (consock == -1)
        {
            break;
        }
        printf("consock = %d\n", consock);
        //设置超时为1us
        struct timeval tv;
        tv.tv_sec = 0;
        tv.tv_usec = 1;
        ret = setsockopt(consock, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
        pthread_t cid;
        ret = pthread_create(&cid, NULL, ChooseCmd, (void*)(&consock));
        if (ret != 0)
        {
            printf("Thread Created Error!\n");
            break;
        }
        pthread_detach(cid);
        usleep(100);
    }
    return 0;
}
